﻿using System;
using System.Linq.Expressions;

namespace Ags.Mvvm
{
    public static class Extensions
    {
        public static string PropertyName<TClass, TProperty>(this Expression<Func<TClass, TProperty>> expression)
        {
            // Text des Lambda-Ausdrucks
            var memberExp = expression.Body as MemberExpression;
            // Name des Felds oder Propertys auf das im Lambda-Ausdruck zugegriffen wird
            if (memberExp != null)
                return memberExp.Member.Name;
            // Ausnahme für DateTime
            var unaryExp = expression.Body as UnaryExpression;
            if (unaryExp != null)
            {
                memberExp = unaryExp.Operand as MemberExpression;
                if (memberExp != null)
                    return memberExp.Member.Name;
            }
            throw new ArgumentException("'expression' should be a member expression or a method call expression.", "expression");
        }
    }
}
